package com.dz.lm.service.userapply.impl;

import com.dz.lm.common.dto.PageDto;
import com.dz.lm.common.dto.UserApplyDTO;
import com.dz.lm.common.dto.UserOrderDTO;
import com.dz.lm.common.dto.UserProductDTO;
import com.dz.lm.common.exception.DaoException;
import com.dz.lm.common.exception.ServiceException;
import com.dz.lm.common.util.JPushUtils;
import com.dz.lm.common.util.StringUtil;
import com.dz.lm.common.utils.DateUtil;
import com.dz.lm.common.utils.StringUtils;
import com.dz.lm.dao.appLogin.read.AppLoginDao;
import com.dz.lm.dao.product.read.CommonAreaDao;
import com.dz.lm.dao.userapply.write.UserApplyDao;
import com.dz.lm.domain.product.CommonArea;
import com.dz.lm.domain.userapply.UserApply;
import com.dz.lm.domain.userapply.UserApplyExample;
import com.dz.lm.domain.usermessage.UserMessage;
import com.dz.lm.service.moneyBar.impl.MoneyBarServiceImpl;
import com.dz.lm.service.pay.WxPayService;
import com.dz.lm.service.userapply.UserApplyService;
import com.dz.lm.service.usermessage.UserMessageService;
import com.dz.lm.service.userorder.UserOrderService;
import com.dz.lm.service.userproduct.UserProductService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

/**
 * @version 1.8;
 * @author: LDY;
 * @Description;
 * @Date: Created in 2020/3/7 21:27;
 */
@Service("userApplyService")
public class UserApplyServiceImpl implements UserApplyService {
    @Resource(name = "writeUserApplyDao")
    private UserApplyDao writeUserApplyDao;
    @Resource(name = "readUserApplyDao")
    private com.dz.lm.dao.userapply.read.UserApplyDao readUserApplyDao;
    @Autowired
    private UserProductService userProductService;
    @Resource(name = "readAppLoginDao")
    private AppLoginDao rAppLoginDao;
    @Autowired
    private WxPayService wxPayService;
    @Resource(name = "readLoginLogDao")
    private com.dz.lm.dao.log.read.LoginLogDao loginLogDao;
    @Autowired
    private CommonAreaDao readCommonAreaDao;
    @Autowired
    private UserMessageService userMessageService;
    public Logger logger = LogManager.getLogger(getClass());
    @Autowired
    private UserOrderService userOrderService;
    @Override    @Transactional
    public int add(int subUserId,int productId,String remark,String template,String urls,String platform,String province ,String city ,String area ,double price) throws ServiceException {
        int ret = 0;
        UserProductDTO deatil = userProductService.getDetail(0, productId, false);

        //判断申请是否存在被拒绝过
        UserApplyExample ex = new UserApplyExample();
        ex.setOrderByClause("update_time DESC");
        UserApplyExample.Criteria cr = ex.createCriteria();
        cr.andStatusEqualTo(2);//拒绝
        cr.andSubUserIdEqualTo(subUserId);
        cr.andProductIdEqualTo(productId);
        ex.setOrderByClause("update_time desc");
        try {
            List<UserApply> list = readUserApplyDao.selectByExample(ex);
            if (list != null && list.size() > 0) { //判断拒绝时间是否大于30天
                UserApply apply = list.get(0);
                Date time = DateUtil.getDateTimeByDay(apply.getUpdateTime());
                Calendar instance = Calendar.getInstance();
                instance.setTime(time);
                instance.add(Calendar.DAY_OF_MONTH, 30);
                Date time1 = instance.getTime();
                if (time1.compareTo(new Date()) > 0) {
                    return -998;
                }
            }
        } catch (DaoException e) {
            e.printStackTrace();
        }
        UserApply ap = new UserApply();
        ap.setSubUserId(subUserId);
        if (deatil.getProductType() == 1) {
            ap.setProductId(productId);
            ap.setSupUserId(deatil.getUserId());

        } else {
            ap.setProductId(deatil.getSuperId());
            ap.setAgentUid(deatil.getUserId());
            ap.setSupUserId(deatil.getSource());
        }

        ap.setRePoint(deatil.getReturnPoint());
        ap.setRemark(remark);
        ap.setTemplate(template);
        if(deatil.getApplyReview() == 1){ //产品不需审核
            ap.setStatus(3); //已成交
            if(!StringUtil.containEmpty(deatil.getApplyMessage()) && deatil.getPrice() == 0){ //添加私信
                UserMessage message = new UserMessage();
                message.setUserId(subUserId);
                message.setSendUid(deatil.getSource());
                message.setMessage(deatil.getProductName()+"的申请推送:  "+deatil.getApplyMessage());
                message.setCreateTime(DateUtil.getTimeStr(new Date()));
                userMessageService.add(message);
            }

        }else {
            ap.setStatus(1); //待结单
        }
        if(deatil.getPrice() > 0){
            ap.setStatus(5); //未支付
        }
        ap.setUrls(urls);
        ap.setHandleDto(1);
        ap.setApplyDto(0);
        ap.setAgnetDto(1);
        ap.setRealPrice(price);
        ap.setCostPrice(deatil.getPrice());
        if (!"100000".equals(province)) { //全国：100000
            ap.setProvince(province);
            //全北京 天津 上海 重庆
            if (!"".equals(city) && !"110100".equals(city) && !"120100".equals(city) && !"310100".equals(city) && !"500100".equals(city))
                ap.setCity(city);
        }
        ap.setArea(area);
        ap.setCreateTime(DateUtil.getTimeStr(new Date()));
        try {
            ret = writeUserApplyDao.insertSelective(ap);
            if (ret > 0) { //添加推送
                ret = ap.getApplyId();
                if(price > 0){
                    userOrderService.add(ret,-1,price,subUserId,deatil.getSource(),"");
                }
                Map<String, Object> insertParam = new HashMap<String, Object>();
                insertParam.put("userId", deatil.getSource());
                //  insertParam.put("userId", subUserId);
                insertParam.put("platform", platform);
                insertParam.put("type", 1);//申请提交

                Runnable runable = new UserApplyServiceImpl.AsyncThread(insertParam);
                runable.run();
            }
        } catch (DaoException e) {
            e.printStackTrace();
        }
        return ret;
    }
    @Transactional
    @Override
    public PageDto query(int pageNum, int rows, int supUserId, int subUserId, int agentUid, int productId, int status) throws ServiceException {
        PageDto pageDto = new PageDto();
        PageHelper.startPage(pageNum, rows);
        UserApplyExample ex = new UserApplyExample();
        ex.setOrderByClause("create_time desc");
        UserApplyExample.Criteria cr = ex.createCriteria();
        if (supUserId > 0) {
            cr.andSupUserIdEqualTo(supUserId);
            if (agentUid == 0) {
                UserApplyExample.Criteria ocr = ex.createCriteria();
                ocr.andAgentUidEqualTo(supUserId);
                if (subUserId > 0) {
                    ocr.andSubUserIdEqualTo(subUserId);
                }
                if (status > 0) {
                    ocr.andStatusEqualTo(status);
                }
                ex.or(ocr);
            }

        }
        if (subUserId > 0) {
            cr.andSubUserIdEqualTo(subUserId);
        }

        if (status > 0) {
            cr.andStatusEqualTo(status);
        }
        if (agentUid > 0) {
          /*  UserApplyExample.Criteria ocr = ex.createCriteria();
            ocr.andAgentUidEqualTo(agentUid);
            if(status >0){
                ocr.andStatusEqualTo(status);
            }
            if(subUserId >0){
                ocr.andSubUserIdEqualTo(subUserId);
            }
            ex.or(ocr);*/
            cr.andAgentUidEqualTo(agentUid);
        }
        try {
            List<UserApply> applies = readUserApplyDao.selectByExample(ex);
            if (applies != null && applies.size() > 0) {
                PageInfo pageInfo = new PageInfo(applies);
                List<UserApplyDTO> dtos = new ArrayList();
                for (UserApply apply : applies) {
                    UserApplyDTO dto = new UserApplyDTO();
                    BeanUtils.copyProperties(apply, dto);
                    setExt(dto);
                    dtos.add(dto);
                }
                pageDto.setInfo(pageInfo);
                pageDto.setList(dtos);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageDto;
    }
    @Transactional
    @Override
    public int handleApply(int applyId, int status, double amount, int productId, String remark, UserApplyDTO dto, String applyContent,String platform) throws ServiceException {
        int ret = 0;
        UserApply apply = new UserApply();
        apply.setApplyId(applyId);
        apply.setApplyDto(1);
        apply.setAgnetDto(1);
        if (!StringUtil.containEmpty(remark)) {
            apply.setRemark(remark);
        }
        apply.setUpdateTime(DateUtil.getTimeStr(new Date()));
        try {
            if (status == 3) { //成交
                UserProductDTO product = userProductService.getDetail(0, productId, false);
                BigDecimal amountC = new BigDecimal(amount);
                BigDecimal returnPoint = new BigDecimal(product.getReturnPoint());
                BigDecimal re_point = null;
                re_point = amountC.multiply(returnPoint);
                apply.setAmount(amount);
                DecimalFormat df1 = new DecimalFormat("0.00");
                apply.setRePoint(product.getReturnPoint());
                if (dto.getAgentUid() == 0 || dto.getRePoint() == 0) { //当没有代理人，或者代理返点为0的时候，状态成交。不然状态再成交完成是改变
                    apply.setStatus(3);
                }
                if( !StringUtil.containEmpty(applyContent)){ //申请通过有私信
                    UserApply userApply = readUserApplyDao.selectByPrimaryKey(applyId);
                    UserMessage message = new UserMessage();
                    message.setUserId(userApply.getSubUserId());
                    message.setSendUid(userApply.getSupUserId());
                    message.setMessage(product.getProductName()+" 的申请推送: "+applyContent);
                    message.setCreateTime(DateUtil.getTimeStr(new Date()));
                    userMessageService.add(message);
                }
                ret = writeUserApplyDao.updateByPrimaryKeySelective(apply);

            } else {
                apply.setStatus(status);
                ret = writeUserApplyDao.updateByPrimaryKeySelective(apply);
            }
            if (ret > 0) { //向申请人发送push
                Map<String, Object> insertParam = new HashMap<String, Object>();
                insertParam.put("userId", dto.getSubUserId());
                insertParam.put("platform", platform);
                insertParam.put("type", 2);//申请处理

                Runnable runable = new UserApplyServiceImpl.AsyncThread(insertParam);
                runable.run();
            }
        } catch (DaoException e) {
            e.printStackTrace();
        }
        return ret;
    }
    @Transactional
    @Override
    public int querCount(int supUserId, int subUserId, int agentUid, int productId, int status, boolean isAgent, boolean isEffect, boolean isHandle, int applyDot, int handleDot) throws ServiceException {
        int count = 0;
        UserApplyExample ex = new UserApplyExample();
        UserApplyExample.Criteria cr = ex.createCriteria();
        if (supUserId > 0) {
            cr.andSupUserIdEqualTo(supUserId);
            if(handleDot > 0){ //查询作为处理人的红点
                cr.andHandleDtoEqualTo(1);
            }
            if (isAgent) { //包含代理
                UserApplyExample.Criteria ocr = ex.createCriteria();
                ocr.andAgentUidEqualTo(supUserId);
                if (subUserId > 0) {
                    ocr.andSubUserIdEqualTo(subUserId);
                }
                if (status > 0) {
                    ocr.andStatusEqualTo(status);
                }
                if(handleDot > 0){ //作为代理人的红点
                    ocr.andAgnetDtoEqualTo(1);
                }
                ex.or(ocr);
            }
        }
        if(agentUid > 0){
            cr.andAgentUidEqualTo(agentUid);
        }
        if (productId > 0) {
            cr.andProductIdEqualTo(productId);
        }
        if (subUserId > 0) {
            cr.andSubUserIdEqualTo(subUserId);
        }
        if (status > 0) {
            cr.andStatusEqualTo(status);
        }
        if (isEffect) {
            cr.andStatusNotEqualTo(2);
        }
        if (applyDot > 0) {
            cr.andApplyDtoEqualTo(1);
        }
        if (isHandle) {
            List<Integer> statusList = new ArrayList();
            statusList.add(1);
            statusList.add(4);
            cr.andStatusIn(statusList);
        }
        try {
            count = readUserApplyDao.queryCount(ex);
        } catch (DaoException e) {
            e.printStackTrace();
        }
        return count;
    }

    private void setExt(UserApplyDTO dto) throws Exception {
        //申请人
        Map p1 = new HashMap();
        p1.put("userId", dto.getSubUserId());
        Map user = rAppLoginDao.qryUserInfoByUserId(p1);
        dto.setSubUser(user);
        //申请人
        p1.clear();
        p1.put("userId", dto.getSupUserId());
        Map supUser = rAppLoginDao.qryUserInfoByUserId(p1);
        dto.setSupUser(supUser);
        //产品信息
        UserProductDTO detail = userProductService.getDetail(0, dto.getProductId(), false);
        Map product = new HashMap();
        product.put("productName", detail.getProductName());
        product.put("productId", detail.getProductId());
        product.put("applyMessage", detail.getApplyMessage());
        product.put("agentMessage", detail.getAgentMessage());
        product.put("price", detail.getPrice());

        dto.setProduct(product);
        dto.setCreateTime(dto.getCreateTime().substring(0, dto.getCreateTime().length() - 3));
        //代理人信息
        if (dto.getAgentUid() > 0) {
            p1.clear();
            p1.put("userId", dto.getAgentUid());
            Map agentUser = rAppLoginDao.qryUserInfoByUserId(p1);
            dto.setAgentUser(agentUser);
        }
        //填充地区
        //adress
        if(!StringUtil.containEmpty(dto.getProvince())){
            CommonArea province = readCommonAreaDao.selectByPrimaryKey(Integer.parseInt(dto.getProvince()));
            CommonArea city = null;
            CommonArea area = null;
            if (!StringUtils.isEmpty(dto.getCity())) {
                city = readCommonAreaDao.selectByPrimaryKey(Integer.parseInt(dto.getCity()));
            }
            if(!StringUtil.containEmpty(dto.getArea())){
                area = readCommonAreaDao.selectByPrimaryKey(Integer.parseInt(dto.getArea()));
            }
            String provinceName = province != null ? province.getName():"";
            String cityName = city!= null ?city.getName() :"";
            String areaName = area!= null ?area.getName() :"";
            String adress = provinceName+cityName+areaName;
            dto.setAddress(adress);
        }
        //订单信息
        UserOrderDTO userOrderDTO = userOrderService.get(dto.getApplyId());
        if(userOrderDTO != null){
            dto.setUserOrder(userOrderDTO);
        }
    }

    @Override
    public UserApplyDTO get(int applyId , boolean isDetail) throws ServiceException {
        UserApplyDTO dto = null;
        try {
            UserApply userApply = readUserApplyDao.selectByPrimaryKey(applyId);
            if(userApply != null){
                dto = new UserApplyDTO();
                BeanUtils.copyProperties(userApply, dto);
                if(isDetail){
                    setExt(dto);
                }else {
                    //申请人
                    Map p1 = new HashMap();
                    p1.put("userId", dto.getSubUserId());
                    Map user = rAppLoginDao.qryUserInfoByUserId(p1);
                    dto.setSubUser(user);
                    //申请人
                    p1.clear();
                    p1.put("userId", dto.getSupUserId());
                    Map supUser = rAppLoginDao.qryUserInfoByUserId(p1);
                    dto.setSupUser(supUser);
                    //产品信息
                    UserProductDTO detail = userProductService.getDetail(0, dto.getProductId(), false);
                    Map product = new HashMap();
                    product.put("productName", detail.getProductName());
                    product.put("productId", detail.getProductId());
                    product.put("applyMessage", detail.getApplyMessage());
                    product.put("agentMessage", detail.getAgentMessage());
                    product.put("price", detail.getPrice());
                    product.put("returnPoint", detail.getReturnPoint());

                    dto.setProduct(product);
                    dto.setCreateTime(dto.getCreateTime().substring(0, dto.getCreateTime().length() - 3));
                    //代理人信息
                    if (dto.getAgentUid() > 0) {
                        p1.clear();
                        p1.put("userId", dto.getAgentUid());
                        Map agentUser = rAppLoginDao.qryUserInfoByUserId(p1);
                        dto.setAgentUser(agentUser);
                    }
                    //填充地区
                    //adress
                    if(!StringUtil.containEmpty(dto.getProvince())){
                        CommonArea province = readCommonAreaDao.selectByPrimaryKey(Integer.parseInt(dto.getProvince()));
                        CommonArea city = null;
                        CommonArea area = null;
                        if (!StringUtils.isEmpty(dto.getCity())) {
                            city = readCommonAreaDao.selectByPrimaryKey(Integer.parseInt(dto.getCity()));
                        }
                        if(!StringUtil.containEmpty(dto.getArea())){
                            area = readCommonAreaDao.selectByPrimaryKey(Integer.parseInt(dto.getArea()));
                        }
                        String provinceName = province != null ? province.getName():"";
                        String cityName = city!= null ?city.getName() :"";
                        String areaName = area!= null ?area.getName() :"";
                        String adress = provinceName+cityName+areaName;
                        dto.setAddress(adress);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return dto;
    }
    @Transactional
    @Override
    public UserApplyDTO getDetail(int applyId, int supUid, int subUid, int agentUid) throws ServiceException {
        UserApplyDTO dto = null;
        try {
            UserApply userApply = readUserApplyDao.selectByPrimaryKey(applyId);
            if (userApply != null) {
                dto = new UserApplyDTO();
                BeanUtils.copyProperties(userApply, dto);
                setExt(dto);
                //取消红点
                if (supUid > 0) {
                    userApply.setHandleDto(0);
                }
                if (subUid > 0) {
                    userApply.setApplyDto(0);
                }
                if (agentUid > 0) {
                    userApply.setAgnetDto(0);
                }
                writeUserApplyDao.updateByPrimaryKeySelective(userApply);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dto;
    }

    public class AsyncThread implements Runnable {
        private Map<String, Object> param;

        AsyncThread(Map<String, Object> param) {
            this.param = param;
        }

        @Override
        public void run() {
            try {
                pushMessage(param);
            } catch (ServiceException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 消息推送
     */
    private void pushMessage(Map<String, Object> param) throws ServiceException {
        Map<String, Object> pushInfo = null;
        Map<String, String> map_jp = Maps.newHashMap();
        try {
            pushInfo = loginLogDao.qryPushIdByUserId(param);
            if (pushInfo == null || pushInfo.isEmpty() || pushInfo.get("pushId") == null || "".equals(pushInfo.get("pushId"))) {
                return;
            }
            String pushTitle = "";
            String pushContent = "";
            int type = StringUtil.getInt(param.get("type"), 0);
            if (type == 1) { //1产品申请
                pushTitle = "【微介】产品申请提醒";
                pushContent = "您有新申请，请注意查收";
            }
            if (type == 2) { //产品处理
                pushTitle = "【微介】申请处理提醒";
                pushContent = "您有申请被处理，请注意查收";
            }
            // 推送
            if ("Android".equals(param.get("platform")) || "wexin".equals(param.get("platform"))) {
                // jpush
                String deviceAndro = pushInfo.get("pushId") == null ? "" : pushInfo.get("pushId").toString();
                //push消息
//                JPushUtils.pushAndroidMessageByRegistrationID(pushTitle, pushContent, deviceAndro);
                JPushUtils.pushAndroidNotificationByRegistrationID(pushTitle, pushContent, new HashMap(), deviceAndro);
            } else {
                if(param.get("IOS") != null){
                    String[] deviceIos = param.get("IOS").toString().split(",");
                    JPushUtils.pushIosNotificationByRegistrationID(pushContent, map_jp, deviceIos);
                }
            }
            logger.info("消息推送成功");
        } catch (DaoException e) {
            logger.info("消息推送失败");
            throw new ServiceException(e.getCause());
        }
    }
    @Transactional
    @Override
    public int updateImage(Map map) throws ServiceException {
        int ret = 0;
        int applyId = StringUtil.getInt(map.get("applyId"), 0);
        try {
            UserApply userApply = readUserApplyDao.selectByPrimaryKey(applyId);
            if(userApply != null){
                String url = map.get("image").toString();
                if(StringUtil.containEmpty(url)){
                    return  ret;
                }
                String urls = "";
                if(!StringUtil.containEmpty(userApply.getUrls())){
                    urls = userApply.getUrls()+","+url;
                }else {
                    urls = url;
                }
                userApply.setUrls(urls);
                ret = writeUserApplyDao.updateByPrimaryKeySelective(userApply);
            }
        } catch (DaoException e) {
            e.printStackTrace();
        }
        return ret;
    }

    @Override
    public int queryCompProudctCount(int comPid) throws ServiceException {
        return 0;
    }

    @Override
    public int update(UserApply userApply) throws ServiceException {
        return writeUserApplyDao.updateByPrimaryKeySelective(userApply);
    }
}
